package io.github.fb513.transport.command;

import com.fasterxml.jackson.databind.JsonNode;
import io.github.fb513.common.enums.CommandEnum;
import io.github.fb513.common.model.BaseData;
import io.github.fb513.common.model.LoginData;
import io.github.fb513.common.util.JwtUtils;
import io.github.fb513.transport.config.ImConfig;
import io.github.fb513.transport.model.LoginInfo;
import io.github.fb513.common.model.MessageInfo;
import io.github.fb513.transport.model.UserInfo;
import io.github.fb513.transport.util.JsonUtils;
import io.github.fb513.transport.util.MessageUtils;
import io.github.fb513.transport.util.SessionHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

import java.util.Map;

/**
 * @author fengbo
 * @since 2023/12/25 11:27
 */
public class LoginCommand extends AbstractCommand {

    private final ImConfig imConfig;

    public LoginCommand(CommandChain commandChain, ImConfig imConfig) {
        super(commandChain);
        this.imConfig = imConfig;
    }

    @Override
    public boolean supportsCommand(int command) {
        return CommandEnum.LOGIN.getCommand() == command;
    }

    @Override
    public void executeCommand(ChannelHandlerContext ctx, MessageInfo<JsonNode> msg) {
        // 登录
        LoginInfo loginInfo = MessageUtils.parseMsg(msg, LoginInfo.class);
        // 登录Token和参数校验 TODO
        Map<String, Object> params = JwtUtils.verifyToken(loginInfo.getToken());
        Long userId = Long.valueOf(params.get("userId").toString());
        Integer clientType = Integer.valueOf(params.get("clientType").toString());

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setClientType(clientType);
        userInfo.setConnectState(1);

        ctx.channel().attr(AttributeKey.valueOf(SessionHolder.SESSION_KEY)).set(SessionHolder.getSessionKey(userInfo));

        SessionHolder.save(userInfo, (NioSocketChannel) ctx.channel());

        // 通知业务
        LoginData loginData = new LoginData();
        loginData.setBrokerHost(imConfig.getIpNum());
        loginData.setBrokerPort(imConfig.getPort());
        BaseData<LoginData> baseData = new BaseData<>(userId, clientType, loginData);
        MessageInfo<BaseData<LoginData>> messageInfo = MessageInfo.getJsonMessage(CommandEnum.LOGIN.getCommand(), baseData);
        commandChain.sendToMQAsync(JsonUtils.formatObjToJson(messageInfo));
    }
}
